package main

import (
	"database/sql"
	"log"
	"net/http"
	"os"
	"strconv"

	"github.com/astaxie/beego/grace"
	"github.com/garyburd/redigo/redis"
	_ "github.com/go-sql-driver/mysql"
)

func insert(db *sql.DB, value int) {
	stmt, err := db.Prepare("INSERT INTO `test_redis` (`num`) VALUES (?)")
	defer stmt.Close()

	if err != nil {
		log.Println(err)
		log.Println("prepare err!")
		return
	}
	ret, err := stmt.Exec(value)
	log.Println(ret)

	if err != nil {
		log.Println(err)
		log.Println("exec err!")
		return
	}

}

func code(listName string, id string) (newCode int) {
	// tcp连接redis
	rs, err := redis.Dial("tcp", "127.0.0.1:6379")
	if err != nil {
		log.Println(err)
		log.Println("redis connect error")
		return
	}
	// 操作完后自动关闭
	defer rs.Close()
	// 选择db
	retCode, err := rs.Do("HINCRBY", listName, id, 1)
	if err != nil {
		log.Println(err)
		log.Println("redis error")
		return
	}
	newCode, err = redis.Int(retCode, err)
	log.Println(newCode)
	return
}

func main() {
	//数据库操作
	db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/istore2")
	if err != nil {
		log.Fatalf("Open database error: %s\n", err)
	}
	defer db.Close()

	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		codeNew := code("po", "0557")
		insert(db, codeNew)
		w.Write([]byte("value=>" + strconv.Itoa(codeNew)))
	})

	err = grace.ListenAndServe("127.0.0.1:8081", mux)
	if err != nil {
		log.Println(err)
	}
	log.Println("Server on 8080 stopped")
	os.Exit(0)
}
